﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GPSTrackingWebsiteManager.ClassManager;
using Telerik.Web.UI;

namespace GPSTrackingWebsiteManager.Manager.Pages
{
    public partial class LinealViewInfo : ClassManager.SessionManagerPage
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                beginDateSelected.SelectedDate = DateTime.Now.Date;
                endDateSelected.SelectedDate = DateTime.Now.Date;
                
                GridSortExpression expression = new GridSortExpression();
                expression.FieldName = "Name";
                expression.SetSortOrder("Ascending");
                this.ClientsControlGrid.MasterTableView.SortExpressions.AddSortExpression(expression);
            }
        }

        protected void lbClearFilters_Click(object sender, EventArgs e)
        {
            ClientsControlGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in ClientsControlGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }
            ClientsControlGrid.MasterTableView.Rebind();
        }

        public string getFormatDate(string date)
        {

            string day = date.Substring(0, 2);
            string month = date.Substring(3, 2);
            string year = date.Substring(6, 4);

            return year + '/' + month + '/' + day;
        }

        public bool isDate(string date)
        {
            try
            {
                DateTime.Parse(date);
                return true;
            }
            catch
            {
                return false;
            }
        }

        protected void ClientsControlGrid_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            getInfoGrid();
            resizeGrid();
        }

        protected void resizeGrid(){
            ClientsControlGrid.Height = Unit.Parse((float.Parse(HiddenFieldHeight.Value.ToString()) - 125).ToString());
        }

        protected void btnVPCProcessSearch_Click(object sender, EventArgs e)
        {
            if(getInfoGrid())
                ClientsControlGrid.DataBind();
            resizeGrid();
        }

        protected bool getInfoGrid() {
            SessionManager objSessionManager = getSessionManager();
            int companyID = -1;
            if (objSessionManager != null)
                companyID = objSessionManager.CompanyIDSelectedComboBox;

            try
            {
                if (beginDateSelected.SelectedDate != null)
                {
                    if (!isDate(beginDateSelected.SelectedDate.Value.ToString()))
                    {
                        showWarningMessage("La fecha de inicio seleccionada no es válida para la consulta.");
                        return false;
                    }
                }
                else {
                    showInfoMessage("No se ha seleccionado la fecha de inicio para la consulta.");
                    return false;
                }

                if (endDateSelected.SelectedDate != null)
                {
                    if (!isDate(endDateSelected.SelectedDate.Value.ToString()))
                    {
                        showWarningMessage("La fecha de fin seleccionada no es válida para la consulta.");
                        return false;
                    }
                }
                else {
                    showInfoMessage("No se ha seleccionado la fecha de fin para la consulta.");
                    return false;
                }

                if (beginDateSelected.SelectedDate.Value > endDateSelected.SelectedDate.Value)
                {
                    showWarningMessage("La fecha de inicio no puede ser mayor a la fecha de fin.");
                    return false;
                }

                ClientsControlGrid.DataSource = GPSTrackingDBV2Custom.Data.DataRepository.ClientsControlProvider.GetByDatesByCompanyID(beginDateSelected.SelectedDate.Value, endDateSelected.SelectedDate.Value, companyID);

                return true;
                /*if (ClientsControlGrid.MasterTableView.Items.Count > 10)
                {
                    this.ClientsControlGrid.Height = Unit.Percentage(100);
                }
                else
                {
                    this.ClientsControlGrid.Height = Unit.Parse("300px");
                }*/

            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se pudo obtener la información.");
                return false;
            }
        }
        
        protected SessionManager getSessionManager()
        {
            return (SessionManager)HttpContext.Current.Session["SessionManager"];
        }

        protected void lbShowError_Click(object sender, EventArgs e)
        {
            showErrorMessage(HiddenFieldError.Value);
        }

        public void showErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Error", "objWindowsMessageManager.show_Error('" + msg + "','Gráfico Lineal de Clientes...');", true);
        }

        public void showInfoMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Info", "objWindowsMessageManager.show_Info('" + msg + "','Gráfico Lineal de Clientes...');", true);
        }

        public void showWarningMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Warning", "objWindowsMessageManager.show_Warning('" + msg + "','Gráfico Lineal de Clientes...');", true);
        }

        protected void setSessionManager(string username, string gpsImei, DateTime date) {
            SessionManager objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];
            objSessionManager.LinealViewInfo_Username = username;
            objSessionManager.LinealViewInfo_GPSImei = gpsImei;
            objSessionManager.LinealViewInfo_Date = date;
            objSessionManager.LinealViewInfo_DateBegin = beginDateSelected.SelectedDate.Value;
            objSessionManager.LinealViewInfo_DateEnd = endDateSelected.SelectedDate.Value;
            HttpContext.Current.Session["SessionManager"] = objSessionManager;
        }

        protected void btnVPCProcessExecution_Click(object sender, EventArgs e)
        {
            try{
                if (string.IsNullOrEmpty(getUsernameSelected()))
                {
                    showInfoMessage("Debe seleccionar un registro para visualizar el gráfico.");
                }
                else
                {
                    setSessionManager(getUsernameSelected(), getGPSImeiSelected(), DateTime.Parse(getDateSelected()));

                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "openRadWin();", "openRadWin();", true);
                }
                resizeGrid();
                
            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se pudo invocar el Gráfico Lineal.");
            }
        }

        protected string getUsernameSelected()
        {
            try
            {
                foreach (Telerik.Web.UI.GridDataItem selectedItem in ClientsControlGrid.SelectedItems)
                {
                    return selectedItem["Username"].Text;
                }
            }
            catch { }
            return "";
        }

        protected string getGPSImeiSelected()
        {
            try
            {
                foreach (Telerik.Web.UI.GridDataItem selectedItem in ClientsControlGrid.SelectedItems)
                {
                    return selectedItem["GPSImei"].Text;
                }
            }
            catch { }
            return "";
        }

        protected string getDateSelected()
        {
            try
            {
                foreach (Telerik.Web.UI.GridDataItem selectedItem in ClientsControlGrid.SelectedItems)
                {
                    return getFormatDate(selectedItem["Date"].Text);
                }
            }
            catch { }
            return DateTime.Now.ToShortDateString();
        }
    }
}